package calao.storage;

import java.io.PrintWriter;

import calao.util.Cursor;
import calao.util.Cursors;
import calao.util.Printable;

public abstract class RecordBinding<T> 
{
	
	class ObjectCursor implements Cursor<T>, Printable
	{
		final Cursor<Record> cursor;
		ObjectCursor(Cursor<Record> cursor) {
			this.cursor = cursor;
		}
		public void close() {
			cursor.close();
		}
		public void delete() {
			cursor.delete();
		}
		public T get() {
			return toObject(cursor.get());
		}
		public boolean next() {
			return cursor.next();
		}
		public long skipNext(long count) {
			return cursor.skipNext(count);
		}
		public void set(T object) {
			cursor.set(toRecord(object));
		}
		public void printTo(PrintWriter writer) {
			int count = 0;
			while (next()) {
				writer.print(get());
				writer.println();
				count++;
			}
			writer.format("%d objects", count);
		}		
	}
	
	final Class<T> type;

	protected RecordBinding(Class<T> type)
	{
		this.type = type;
	}
	
	abstract public T toObject(Record record);
	
	abstract public Record toRecord(T object);
	
	public Cursor<T> transform(Cursor<Record> cursor)
	{
		return new ObjectCursor(cursor);
	}
	
	public T[] toArray(final Cursor<Record> cursor)
	{
		return Cursors.toArray(transform(cursor), type);
	}
	
}
